package pers.liu.yibandemo.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import pers.liu.yibandemo.entity.Grade;
import pers.liu.yibandemo.mapper.GradeMapper;

import java.util.List;

@Service
public class GradeService extends ServiceImpl<GradeMapper, Grade> {

    @Autowired
    private GradeMapper gradeMapper;

    // 添加成绩信息
    public void addGrade(Grade grade) {
        QueryWrapper<Grade> gradeQueryWrapper = new QueryWrapper<>();
        QueryWrapper<Grade> eq = gradeQueryWrapper.eq("student_id", grade.getStudentId())
                .eq("course_name", grade.getCourseName())
                .eq("score", grade.getScore());
        Grade one = gradeMapper.selectOne(eq);
        if(one!=null){
            throw new IllegalStateException("A grade with the same student ID, course name, and score already exists.");
        }
        gradeMapper.insert(grade);
    }

    // 查询所有学生成绩信息
    public List<Grade> getAllGrades() {
        return gradeMapper.selectList(null);
    }
    // 分页查询全部
    public IPage<Grade> getGradesByPage(int pageNum,int pageSize){
        Page<Grade> page = new Page<>(pageNum, pageSize);
        Page<Grade> result = gradeMapper.selectPage(page, null);
        return result;
    }
    // 根据学生ID查询学生成绩信息
    public List<Grade> getGradesByStudentId(String studentId) {
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", studentId);
        return gradeMapper.selectList(queryWrapper);
    }

    // 根据学期和学生ID查询成绩信息
    public List<Grade> getGradesBySemesterAndStudentId(String semester, String studentId) {
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("semester_name", semester)
                .eq("student_id", studentId);
        return gradeMapper.selectList(queryWrapper);
    }

    // 根据课程和学生ID查询成绩信息
    public List<Grade> getGradesByCourseAndStudentId(String course, String studentId) {
        QueryWrapper<Grade> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("course_name", course)
                .eq("student_id", studentId);
        return gradeMapper.selectList(queryWrapper);
    }

    // 删除成绩
    public void deleteGrade(Long gradeId) {
        gradeMapper.deleteById(gradeId);

    }
    // 更新成绩
    public void updateGrade(Grade grade) {

        gradeMapper.updateById(grade);

    }
}
